package com.example.myui.activity;

import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.myui.R;
import com.example.myui.fragment.Fragment0;
import com.example.myui.fragment.Fragment1;
import com.example.myui.fragment.Fragment2;
import com.example.myui.fragment.Fragment3;

import java.util.ArrayList;
import java.util.List;

public class BannnerActivity extends AppCompatActivity {
    private static final String TAG = BannnerActivity.class.getSimpleName();
    private Handler mHandler = new Handler();
    private ViewPager viewpager;
    private ArrayList<Fragment> fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bannner);
        fragments = new ArrayList<>();
        fragments.add(new Fragment0());
        fragments.add(new Fragment1());
        fragments.add(new Fragment2());
        fragments.add(new Fragment3());
        viewpager = findViewById(R.id.viewpager_banner);
        BannerAdapter adapter = new BannerAdapter(fragments, getSupportFragmentManager());
        viewpager.setAdapter(adapter);

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                int currentItem = viewpager.getCurrentItem();
                if (viewpager.getCurrentItem() == fragments.size()-1) {
                    viewpager.setCurrentItem(0, true);
                    mHandler.postDelayed(this,2000);
                    Log.i(TAG, "run: " );
                } else {
                    viewpager.setCurrentItem(currentItem + 1, true);
                    mHandler.postDelayed(this, 2000);
                }
            }
        }, 2000);


    }

    private class BannerAdapter extends FragmentStatePagerAdapter {

        private List<Fragment> mFragment = new ArrayList<>();

        public BannerAdapter(ArrayList<Fragment> fragments, FragmentManager supportFragmentManager) {
            super(supportFragmentManager);
            this.mFragment = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return mFragment.get(position);
        }

        @Override
        public int getCount() {
            return mFragment.size();
        }
    }
}
